package com.androsz.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.widget.Toast;

import com.androsz.andslr.R;

public class IntentUtil {
	/**
	 * Indicates whether the specified action can be used as an intent. This
	 * method queries the package manager for installed packages that can
	 * respond to an intent with the specified action. If no suitable package is
	 * found, this method returns false.
	 * 
	 * @param context
	 *            The application's environment.
	 * @param action
	 *            The Intent action to check for availability.
	 * 
	 * @return True if an Intent with the specified action can be sent and
	 *         responded to, false otherwise.
	 */
	public static boolean doesIntentHaveReceivers(final Context context,
			final String action) {
		final PackageManager packageManager = context.getPackageManager();
		final Intent intent = new Intent(action);
		final List<ResolveInfo> list = packageManager.queryBroadcastReceivers(
				intent, 0);
		return list.size() > 0;
	}

	public static boolean OIPickDirectory(final Fragment fragment,
			int requestCode, String initialDirectoryUri) {
		Intent intent = new Intent("org.openintents.action.PICK_DIRECTORY");
		if (initialDirectoryUri == null) {
			intent.setData(Uri.parse("file:///sdcard"));
		} else {
			intent.setData(Uri.parse("file:///" + initialDirectoryUri));
		}
		intent.putExtra("org.openintents.extra.TITLE",
				fragment.getString(R.string.pick_directory));
		intent.putExtra("org.openintents.extra.BUTTON_TEXT",
				fragment.getString(R.string.use_this_directory));
		try {
			fragment.startActivityForResult(intent, requestCode);
			return true;
		} catch (ActivityNotFoundException anfe) {
			new AlertDialog.Builder(fragment.getActivity())
					.setMessage(R.string.oi_file_manager_required)
					.setPositiveButton(
							R.string.download_from_the_android_market,
							new OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									final Uri marketUri = Uri.parse(fragment
											.getString(R.string.uri_org_openintents_filemanager));
									final Intent marketIntent = new Intent(
											Intent.ACTION_VIEW, marketUri);
									marketIntent
											.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
									marketIntent
											.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
									marketIntent
											.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
									fragment.startActivity(marketIntent);
								}
							}).show();
			return false;
		}
	}
	
	public static boolean OIPickDirectory(final Activity activity,
			int requestCode, String initialDirectoryUri) {
		Intent intent = new Intent("org.openintents.action.PICK_DIRECTORY");
		if (initialDirectoryUri == null) {
			intent.setData(Uri.parse("file:///sdcard"));
		} else {
			intent.setData(Uri.parse("file:///" + initialDirectoryUri));
		}
		intent.putExtra("org.openintents.extra.TITLE",
				activity.getString(R.string.pick_directory));
		intent.putExtra("org.openintents.extra.BUTTON_TEXT",
				activity.getString(R.string.use_this_directory));
		try {
			activity.startActivityForResult(intent, requestCode);
			return true;
		} catch (ActivityNotFoundException anfe) {
			new AlertDialog.Builder(activity)
					.setMessage(R.string.oi_file_manager_required)
					.setPositiveButton(
							R.string.download_from_the_android_market,
							new OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									final Uri marketUri = Uri.parse(activity
											.getString(R.string.uri_org_openintents_filemanager));
									final Intent marketIntent = new Intent(
											Intent.ACTION_VIEW, marketUri);
									marketIntent
											.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
									marketIntent
											.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
									marketIntent
											.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
									activity.startActivity(marketIntent);
								}
							}).show();
			return false;
		}
	}
	
	public static void shareBitmap(final Context c, final Bitmap b) {
        File externalCacheDir = c.getExternalCacheDir();
        if (externalCacheDir == null) {
            Toast.makeText(c, "Error writing to USB/external storage.",
                    Toast.LENGTH_SHORT).show();
            return;
        }

        // Prevent media scanning of the cache directory.
        final File noMediaFile = new File(externalCacheDir, ".nomedia");
        try {
            noMediaFile.createNewFile();
        } catch (IOException e) {
        }

        // Write the bitmap to temporary storage in the external storage directory (e.g. SD card).
        // We perform the actual disk write operations on a separate thread using the
        // {@link AsyncTask} class, thus avoiding the possibility of stalling the main (UI) thread.

        final File tempFile = new File(externalCacheDir, "tempfile.jpg");

        new AsyncTask<Void, Void, Boolean>() {
            /**
             * Compress and write the bitmap to disk on a separate thread.
             * @return TRUE if the write was successful, FALSE otherwise.
             */
            protected Boolean doInBackground(Void... voids) {
                try {
                    FileOutputStream fo = new FileOutputStream(tempFile, false);
                    if (!b.compress(Bitmap.CompressFormat.JPEG, 60, fo)) {
                        Toast.makeText(c, "Error writing bitmap data.",
                                Toast.LENGTH_SHORT).show();
                        return Boolean.FALSE;
                    }
                    return Boolean.TRUE;

                } catch (FileNotFoundException e) {
                    Toast.makeText(c, "Error writing to USB/external storage.",
                            Toast.LENGTH_SHORT).show();
                    return Boolean.FALSE;
                }
            }

            /**
             * After doInBackground completes (either successfully or in failure), we invoke an
             * intent to share the photo. This code is run on the main (UI) thread.
             */
            protected void onPostExecute(Boolean result) {
                if (result != Boolean.TRUE) {
                    return;
                }

                Intent shareIntent = new Intent(Intent.ACTION_SEND);
                shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(tempFile));
                shareIntent.setType("image/jpeg");
                c.startActivity(Intent.createChooser(shareIntent, "Share photo"));
            }
        }.execute();
    }
}
